package com.draven.tongzhou.controller

import com.draven.tongzhou._
import com.draven.tongzhou.common.SysResp
import com.draven.tongzhou.utils.RandomValidateCodeUtil
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.{ApplicationEventPublisher, ApplicationEventPublisherAware}
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{RequestMapping, RequestParam, ResponseBody}
import org.springframework.web.servlet.ModelAndView

/**
  * 登录相关
  * Created by Draven on 2018/7/12.
  * Email:hjx@qiandw.com
  */
@Controller
@RequestMapping(value = Array("/passport"))
class LoginController extends CommonController with ApplicationEventPublisherAware {

  val logger = LoggerFactory.getLogger(classOf[LoginController])

  var eventPublisher: ApplicationEventPublisher = _

  @RequestMapping(value = Array("/login"))
  def toLoginPage(request: HttpServletRequest): ModelAndView = {
    toPage("/login1")
  }

  /**
    * 获取验证码
    *
    * @param request
    * @param response
    */
  @RequestMapping(value = Array("/getVerify"))
  def getVerify(request: HttpServletRequest, response: HttpServletResponse): Unit = {
    try {
      response.setContentType("image/jpeg") //设置相应类型,告诉浏览器输出的内容为图片
      response.setHeader("Pragma", "No-cache") //设置响应头信息，告诉浏览器不要缓存此内容
      response.setHeader("Cache-Control", "no-cache")
      response.setDateHeader("Expire", 0)
      val randomValidateCode = new RandomValidateCodeUtil()
      randomValidateCode.getRandcode(request, response); //输出验证码图片方法
    } catch {
      case e: Exception => logger.error(e.getMessage)
    }
  }

  /**
    * 登录
    *
    * @param request
    * @param username
    * @param password
    * @param verifyCode
    * @return
    */
  @RequestMapping(value = Array("/doLogin"), produces = Array("application/json;charset=UTF-8"))
  @ResponseBody
  def doLogin(request: HttpServletRequest, @RequestParam("username") username: String, @RequestParam("password") password: String, @RequestParam("verifyCode") verifyCode: String): SysResp = {
    val sessionVerify = request.getSession.getAttribute("RANDOMVALIDATECODEKEY").toString
    //    if (!sessionVerify.equalsIgnoreCase(verifyCode)) {
    //      return SysResp(SYS_MSG_VERIFYCODE_ERROR)
    //    }
    //    val user = backstageUserSrv.login(username, password)
    //    if (user._1.code == 200) {
    //      request.getSession().setAttribute(SESSION_USER_KEY, user._2);
    //    }
    //    user._1
    request.getSession().setAttribute(SESSION_USER_KEY, 1);

    SysResp((200, "ok", "200"))
  }

  override def setApplicationEventPublisher(applicationEventPublisher: ApplicationEventPublisher): Unit = {
    this.eventPublisher = applicationEventPublisher
  }
}
